﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using XLuSharpLibrary.CommonFunction;
using BHair.Business.Table;
using BHair.Business.BaseData;
using System.IO;
using System.Data.SqlClient;
using System.Configuration;

namespace BHair.Business
{
    public partial class frmPay_OK : Form
    {
        private Pays _objPay = new Pays();//消费单据信息
        private decimal _dZero = 0;
        private string dy = null;
        private string d = null;
        private string tt = null;

        public frmPay_OK(string payid)
        {
            InitializeComponent();
            this._objPay = new Pays(payid);//保存消费单据
        }

        private void frmPay_OK_Load(object sender, EventArgs e)
        {
            string time3 = DateTime.Now.ToShortDateString().ToString();
            tt = "**********测试门店*********" + "\r" + "\n" + "账单号：" + this._objPay.PayID + "\r" + "\n" + "时间：" + time3 + "\r" + "\n" + "\r" + "\n" + "名称"+"\t"+"\t"+"数量"+"\t"+"金额" + "\r" + "\n" + "\r" + "\n";
            if (this._objPay.MemberId == "0")
            {
                this.lblName.Text += "非会员(散客)";
                this.lblBalance.Text += "￥0.00";
                this.rbtnBalance.Enabled = false;
                this.rbtnAnd.Enabled = false;
                this.LoadCashPay();//初始化现金支付数据
            }
            else //会员
            {
                this.lblName.Text += this._objPay.ClientName;
                this.lblBalance.Text += this._objPay.Member.Balance.ToString("f2");
                if (this._objPay.Member.Balance >= this._objPay.Money)
                {
                    //余额大于等于消费金额
                    this.rbtnBalance.Checked = true;
                    this.rbtnAnd.Enabled = true;
                    this.LoadBalancePay();
                }
                else if (this._objPay.Member.Balance < this._objPay.Money)
                {
                    //余额小于消费金额
                    this.rbtnBalance.Enabled = false;
                    this.LoadCashPay();
                }
            }
            this.lblPayID.Text += this._objPay.PayID;
            this.lblMoney.Text += "￥" + this._objPay.Money.ToString("f2");//消费金额
        }


        #region 支付方式...

        /// <summary>现金</summary>
        private void rbtnCash_CheckedChanged(object sender, EventArgs e)
        {
            if (this.rbtnCash.Checked)
            {
                this.LoadCashPay();
            }
        }

        /// <summary>初始化现金支付数据</summary>
        private void LoadCashPay()
        {
            this.numPayBalance.Value = 0;
            this.numPayMoney.Value = this._objPay.Money;
            this.txtCash.Text = this._objPay.Money.ToString("f2");

            this.numPayMoney.Minimum = 0;

            this.numPayBalance.Enabled = false;
            this.numPayMoney.Enabled = false;
            this.txtCash.ReadOnly = false;
        }

        /// <summary>余额</summary>
        private void rbtnBalance_CheckedChanged(object sender, EventArgs e)
        {
            if (this.rbtnBalance.Checked)
            {
                this.LoadBalancePay();
            }
        }

        /// <summary>初始化余额支付数据</summary>
        private void LoadBalancePay()
        {
            this.numPayBalance.Value = this._objPay.Money;
            this.numPayMoney.Value = 0;
            this.txtCash.Text = "0.00";

            this.numPayMoney.Minimum = 0;

            this.numPayBalance.Enabled = false;
            this.numPayMoney.Enabled = false;
            this.txtCash.ReadOnly = true;
        }

        /// <summary>现金+余额</summary>
        private void rbtnAnd_CheckedChanged(object sender, EventArgs e)
        {
            if (this.rbtnAnd.Checked)
            {
                this.LoadCashPay();
                this.numPayBalance.Enabled = true;
                this.numPayMoney.Enabled = true;
                this.txtCash.ReadOnly = false;

                if (this._objPay.Member.Balance < this._objPay.Money)
                {
                    this.numPayBalance.Maximum = this._objPay.Member.Balance;
                    this.numPayMoney.Minimum = this._objPay.Money - this._objPay.Member.Balance;
                }
                else
                {
                    this.numPayBalance.Maximum = this._objPay.Money;
                }
                this.numPayMoney.Maximum = this._objPay.Money;
            }
        }

        #endregion

        /// <summary>确定</summary>
        private void btnOK_Click(object sender, EventArgs e)
        {
            if (chuanzhi.isfo == 0)
            {
                jkc();

                Pays objPay = new Pays();
                objPay.PayID = this._objPay.PayID;
                objPay.Cash = decimal.Parse(this.txtCash.Text.Trim());//实收金额
                objPay.Zero = this._dZero;// (decimal.Parse(this.txtCash.Text.Trim()) - this.numPayMoney.Value).ToString("f2");
                objPay.Remark = "";
                if (this.rbtnCash.Checked)
                {
                    objPay.PayType = 0;//现金
                }
                else if (this.rbtnBalance.Checked || this.rbtnAnd.Checked)
                {
                    objPay.PayType = 1;//余额
                }
                //判断现金消费
                if (objPay.Cash < this.numPayMoney.Value)
                {
                    MessageBox.Show("【实收金额】必须大于等于【应收金额】", "消息", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    this.txtCash.Focus();
                    return;
                }
                if (this.rbtnAnd.Checked)
                {
                    objPay.Remark = "\n[现金+余额]现金：" + this.numPayMoney.Value.ToString("f2") + "；刷卡：" + this.numPayBalance.Value.ToString("f2") + "；";
                    Deposit objDeposit = new Deposit();
                    objDeposit.Remark = "[现金+余额]现金：" + this.numPayMoney.Value.ToString("f2") + "；刷卡：" + this.numPayBalance.Value.ToString("f2") + "；消费单号：" + this._objPay.PayID;
                    objDeposit.Mode = 0;
                    objDeposit.MemberID = this._objPay.MemberId;
                    objDeposit.Money = this.numPayMoney.Value;
                    objDeposit.Date = this._objPay.PayDate;
                    objDeposit.InsertDeposit();
                }
                if (objPay.UpdatePaysOK() > 0)
                {
                    new Member().UpdateBalance(this._objPay.MemberId);
                    new Member().UpdateLastTime(this._objPay.MemberId, this._objPay.PayDate);
                }
                DialogResult = DialogResult.OK;


                //kkc();
                if (radioButton1.Checked)
                {
                    dyf();
                }


                this.Close();
            }
            else 
            {
                MessageBox.Show("库存不足");
            }
            
        }

        #region 计算找零金额...

        private void txtCash_TextChanged(object sender, EventArgs e)
        {
            this.FindZeroCash();
        }

        private void txtCash_KeyPress(object sender, KeyPressEventArgs e)
        {
            NumericClass.NumberAccpter(sender, e, true);
        }

        /// <summary>计算找零。</summary>
        private void FindZeroCash()
        {
            decimal dCash = 0;
            if (this.txtCash.Text.Trim() != "")
            {
                dCash = decimal.Parse(this.txtCash.Text.Trim());
            }
            else
            {
                this.txtCash.Text = "0";
                this.txtCash.SelectionStart = this.txtCash.Text.Length;
            }
            this._dZero = dCash - this.numPayMoney.Value;
            if (this.rbtnBalance.Checked)
            {
                this._dZero = 0;
            }
            this.lblZero.Text = "￥" + this._dZero.ToString("f2");
        }

        #endregion

        /// <summary>取消关闭窗体。</summary>
        private void btnCancel_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void numPayBalance_ValueChanged(object sender, EventArgs e)
        {
            this.numPayMoney.Value = this._objPay.Money - this.numPayBalance.Value;
            this.txtCash.Text = this.numPayMoney.Value.ToString("f2");
            this.FindZeroCash();
        }
        
        ///// <summary>变更刷卡金额</summary>
        //private void numPayBalance_KeyUp(object sender, KeyEventArgs e)
        //{
        //    this.numPayMoney.Value = this._objPay.Money - this.numPayBalance.Value;
        //    this.FindZeroCash();
        //}

        private void numPayMoney_ValueChanged(object sender, EventArgs e)
        {
            this.numPayBalance.Value = this._objPay.Money - this.numPayMoney.Value;
            this.FindZeroCash();
        }

        private void numPayMoney_KeyUp(object sender, KeyEventArgs e)
        {
            this.numPayBalance.Value = this._objPay.Money - this.numPayMoney.Value;
            this.FindZeroCash();
        }
    
        DataTable dt1 = new DataTable();
        DataSet ds = new DataSet();
        //实现消费扣减库存
        public void kkc() 
        {
            //定义数据库查询语句查询消费的库存数
            //再根据消费的商品ID来扣减对应库存数量
            
            //
            string sqlcc = string.Format("select items.iid,paydetails.pdnum from items left join paydetails on items.iid=paydetails.pdiid where pdpid='{0}'",this._objPay.PayID);
            
            string constr = ConfigurationManager.ConnectionStrings["BHair.Properties.Settings.BHairDBConnectionString"].ConnectionString;
            SqlConnection sqlconn = new SqlConnection(constr);
           
            SqlDataAdapter sda = new SqlDataAdapter(sqlcc,sqlconn);
            DataTable dt1 = new DataTable();
            int spid = 0;
            int kcsl = 0;
            int kc = 0;
           
            sda.Fill(dt1);
            sqlconn.Close();
            for (int i = 0; i < dt1.Rows.Count;i++ )
            {
                sqlconn.Open();
                SqlCommand comm1 = new SqlCommand(sqlcc, sqlconn);
                SqlDataReader reader = comm1.ExecuteReader();
                while (reader.Read())
                {
                   spid = Int32.Parse(reader["iid"].ToString().Trim());
                   kcsl = Int32.Parse(reader["pdnum"].ToString().Trim());
                
                
                string sqlckc =string.Format( "SELECT[iamount] FROM [BHairDB].[dbo].[items] where iid={0}",spid);
                SqlCommand comm2=new SqlCommand(sqlckc,sqlconn);
                reader.Close();
                SqlDataReader re1 = comm2.ExecuteReader();
                while(re1.Read())
                {
                    kc =Int32.Parse( re1["iamount"].ToString().Trim());
                
                re1.Close();
                int kcup = kc-kcsl;
                string sqlup =string.Format( "UPDATE [BHairDB].[dbo].[items]SET [iamount] = {0} WHERE iid={1}",kcup,spid);
                try 
                {
                    SqlCommand comm3 = new SqlCommand(sqlup,sqlconn);
                    comm3.ExecuteNonQuery();
                    sqlconn.Close();
                }catch(Exception e2)
                {
                    sqlconn.Close();
                    MessageBox.Show(e2.Message);
                }
                }
                
            }
                
            }
            sqlconn.Close();
            MessageBox.Show("结算成功");
        }
        public void jkc() 
        {
            int spid = 0;//商品ID
            decimal spkc = 0;//商品库存
            decimal xsnum = 0;
            //定义语句查询出售的商品明细
            string sqlcc = string.Format("select items.iid from items left join paydetails on items.iid=paydetails.pdiid where pdpid='{0}'", this._objPay.PayID);
            string sqlcc2 = string.Format("select items.iid,paydetails.pdnum from items left join paydetails on items.iid=paydetails.pdiid where pdpid='{0}'", this._objPay.PayID);
            string constr = ConfigurationManager.ConnectionStrings["BHair.Properties.Settings.BHairDBConnectionString"].ConnectionString;
            SqlConnection conn5 = new SqlConnection(constr);
            conn5.Open();
            SqlDataAdapter sda5 = new SqlDataAdapter(sqlcc,conn5);
            DataTable dt5 = new DataTable();
            
            sda5.Fill(dt5);//填充
            int row = dt5.Rows.Count;
            //conn5.Close();
            for (int z = 0; z < dt5.Rows.Count;z++ )//循环更改数据库中库存数量
            {
                SqlConnection conn6 = new SqlConnection(constr);
                conn6.Open();
                SqlCommand comm5 = new SqlCommand(sqlcc2,conn6);
                SqlDataReader sdr = comm5.ExecuteReader();
                while(sdr.Read())
                {
                    spid =Int32.Parse(sdr["iid"].ToString().Trim());
                    xsnum = decimal.Parse(sdr["pdnum"].ToString().Trim());
                    //根据商品ID查询对应商品的库存数量
                    //sdr.Close();
                    string sqlkc = string.Format("SELECT[iamount] FROM [BHairDB].[dbo].[items] where iid={0}",spid);//查询商品表中库存数量
                    SqlConnection conn7 = new SqlConnection(constr);
                    conn7.Open();
                    SqlCommand comm6 = new SqlCommand(sqlkc,conn7);
                    SqlDataReader sdr1 = comm6.ExecuteReader();
                    
                    while(sdr1.Read())
                    {
                        spkc =decimal.Parse( sdr1["iamount"].ToString().Trim());
                        if (spkc >= xsnum)
                        {
                            

                            
                            decimal kcnum = spkc - xsnum;//库存数量-销售数量
                            //定义语句 将kcnum 更新到库存表
                            //sdr1.Close();
                            string sqlupkc = string.Format("UPDATE [BHairDB].[dbo].[items]SET [iamount] = {0} WHERE iid={1}", kcnum, spid);
                            SqlConnection conn8 = new SqlConnection(constr);
                            conn8.Open();
                            SqlCommand comm7 = new SqlCommand(sqlupkc, conn8);
                            comm7.ExecuteNonQuery();
                            z++;
                            break;
                        }
                        else 
                        {
                            MessageBox.Show("库存不足");
                        }
                        break;
                    }
                    //sdr1.Close();

                    //break;
                }
                
                //sdr.Dispose();
                
                //z++;
            }
            
            MessageBox.Show("ok");
            this.Close();

        }
        //打印消费小票
        public void DaYin() 
        {
            //读取数据库连接字符串
            string constr = ConfigurationManager.ConnectionStrings["BHair.Properties.Settings.BHairDBConnectionString"].ConnectionString;
            SqlConnection conn = new SqlConnection(constr);
            conn.Open();
            //定义数据库查询语句查询消费商品

            string pid = this._objPay.PayID;
            string stryj =string.Format( "select items.iname,paydetails.pdnum,paydetails.pmoney from items left join paydetails on items.iid=paydetails.pdiid where pdpid='{0}'",pid);
            SqlDataAdapter sda = new SqlDataAdapter(stryj,conn);
            string str1 = "";
            sda.Fill(dt1);
            //string xfhj = this._objPay.Money;
            for(int i=0;i<dt1.Rows.Count;i++)
            {
                sda.Fill(ds);
                string spm = ds.Tables[0].Rows[i]["iname"].ToString();
                /*
                 *判断商品名称字符串长度
                 *1.如果字符串长度超过6，则截取前6个字符
                 *2.如果字符串长度小于6，则自动填充空格
                 */
                if(spm.Length>6)
                {
                     str1 = spm.Substring(0, 6);
                }else
                {
                    str1 = spm.PadRight(6);
                }
               
                decimal je =decimal.Round( decimal.Parse(ds.Tables[0].Rows[i]["pmoney"].ToString()),2);
                int num =Int32.Parse( ds.Tables[0].Rows[i]["pdnum"].ToString());
                d = d + str1+ "\t" + num + "\t" + je + "\n";
            }
            dy = tt + d + "-----------------------" + "\r" + "\n" + string.Format("消费合计：{0}" + "\r" + "\n" + "找零:{1}" + "\r" + "\n" + "卡号:{2}" + "\r" + "\n" + "余额：" + "\r" + "\n" + "积分：" + "\r" + "\n" + "*****欢迎您下次光临*****", decimal.Round(this._objPay.Money, 2).ToString(), decimal.Round(this._dZero, 2).ToString(), this._objPay.MemberId);

        }

        private void printDocument1_PrintPage(object sender, System.Drawing.Printing.PrintPageEventArgs e)
        {
            
            
            StringReader sr = new StringReader(dy);
           
            Graphics g = e.Graphics;//创建画布
           
            Font fnt = new Font("宋体", 8, FontStyle.Bold);
            float left = e.MarginBounds.Left - 85;//左边距
            float top = e.MarginBounds.Top-50;//上边距
            float line = e.MarginBounds.Height / fnt.GetHeight(g);//打印的行数
            int number = 0;//行号
            float y = 0;//每行打印的纵坐标
            string str = "";//每行打印的内容
            
            while ((number < line) && (str = sr.ReadLine()) != null)
            {
                y = top + fnt.GetHeight(g) * number;//找到纵坐标
                g.DrawString(str, fnt, new SolidBrush(Color.Black), left, y);
                number++;
            }
            
        }
        public void dyf() 
        {
            DaYin();
            printPreviewDialog1.Document = this.printDocument1;
            if (this.printPreviewDialog1.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                this.printDocument1 = this.printPreviewDialog1.Document;
            }
        }

        private void btndy_Click(object sender, EventArgs e)
        {
            dyf();
        }
    }
}
